<template>
  <div class="content-container">
    <el-form label-width="auto" :inline="true" class="demo-form-inline">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="运单号" class="full-width">
            <el-input v-model="filters.trackingNumber" placeholder="请输入运单号" class="full-width"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="出发地" class="full-width">
            <el-input v-model="filters.origin" placeholder="请输入出发地" class="full-width"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="目的地" class="full-width">
            <el-input v-model="filters.destination" placeholder="请输入目的地" class="full-width"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="物流商" class="full-width">
            <el-input v-model="filters.logisticId" placeholder="请输入物流商ID" class="full-width"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="状态" class="full-width">
            <el-select v-model="filters.state" placeholder="请选择状态" class="full-width">
              <el-option label="全部" :value="null"></el-option>
              <el-option label="待物流商确认" :value="'待物流商确认'"></el-option>
              <el-option label="待确认" :value="'待确认'"></el-option>
              <el-option label="待配送" :value="'待配送'"></el-option>
              <el-option label="运输中" :value="'运输中'"></el-option>
              <el-option label="已送达" :value="'已送达'"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="类型" class="full-width">
            <el-select v-model="filters.customerType" placeholder="请选择状态" class="full-width">
              <el-option label="全部" :value="null"></el-option>
              <el-option label="仓库" :value="0"></el-option>
              <el-option label="客户" :value="1"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="预计到达时间" class="full-width">
            <el-date-picker
                v-model="filters.departureDate"
                type="daterange"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                class="full-width">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="调拨时间" class="full-width">
            <el-date-picker
                v-model="filters.allocationDate"
                type="daterange"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                class="full-width">
            </el-date-picker>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item class="right full-width" label=" ">
            <el-button-group class="full-width">
              <el-button icon="search" type="primary" plain @click="search" style="width: 50%">查询</el-button>
              <el-button icon="refresh" @click="resetFilters" style="width: 50%">重置</el-button>
            </el-button-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="divider"></div>
    <el-row :gutter="20" class="action-buttons">
      <el-col :span="12">
      </el-col>
    </el-row>
    <el-table :data="currentTableData"
              ref="table"
              style="width: 100%;
              flex: 1"
              :header-cell-style="headerCellStyle"
              @selection-change="handleSelectionChange"
              :default-sort="{ prop: 'hireDate', order: 'descending' }">
      <el-table-column type="selection" :selectable="isSelectable" width="45"/>
      <el-table-column prop="trackingNumber" label="运输单号" width="120" fixed>
        <template v-slot="scope">
          <el-link type="primary" @click="openDetailDialog(scope.row)">{{ scope.row.trackingNumber }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column prop="origin" label="出发地" width="130"></el-table-column>
      <el-table-column prop="destination" label="目的地" width="130"></el-table-column>
      <el-table-column prop="customerType" label="类型" width="90">
        <template v-slot="scope">
          <el-tag
              :type="scope.row.customerType === 0 ? 'success' : scope.row.driverState === 1 ? 'warning' : 'danger'"
              disable-transitions>
            {{ scope.row.customerType === 0 ? '货品' : '商品' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="重量" width="90">
        <template v-slot="scope">
          <span>{{ scope.row.weight }}{{ scope.row.weightUnit }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="transportQuantity" label="数量" width="70"/>
      <el-table-column prop="departureDate" label="预计到货日期" sortable width="140">
        <template v-slot="scope">
          <span>{{ formatDate(scope.row.departureDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="下达日期" sortable width="140">
        <template v-slot="scope">
          <span>{{ formatDate(scope.row.generatedDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="配送单号" width="140">
        <template v-slot="scope">
          <span>{{ scope.row.deliveryId === null ? '暂无': scope.row.deliveryId }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="state" label="状态" min-width="110">
        <template v-slot="scope">
          <el-tag
              :type="scope.row.state === '待运营商确认' ? 'danger'
              : scope.row.state === '待确认' ? 'warning'
              : scope.row.state === '待配送' ? 'info'
              : scope.row.state === '运输中' ? 'success'
              : 'primary'"
              disable-transitions>
            {{
              scope.row.state === '待运营商确认' ? '待确认' :
                  scope.row.state === '待确认' ? '待物流商确认' :
                      scope.row.state
            }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="物流商id" min-width="90">
        <template v-slot="scope">
          <span>{{ scope.row.logisticId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="运费" min-width="90">
        <template v-slot="scope">
          <span>{{ scope.row.feeTemp }}元</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="140">
        <template v-slot="scope">
          <template v-if="scope.row.state === '待运营商确认'">
            <el-button @click="confirmAction(scope.row)" type="text" icon="pointer" style="font-size: 13px">确认
            </el-button>
            <el-button @click="openEditDialog(scope.row, true)" type="text" icon="EditPen" style="font-size: 13px">修改
            </el-button>
          </template>
          <template v-else-if="scope.row.state === '待确认'">
            <el-button @click="openEditDialog(scope.row, false)" type="text" style="font-size: 13px" icon="View">
              查看修改请求
            </el-button>
          </template>
          <template v-else-if="scope.row.state === '运输中'">
            <el-button @click="openLogisticsInfoDialog(scope.row)" type="text" icon="InfoFilled" style="font-size: 13px">物流信息</el-button>
            <el-button @click="changeAction(scope.row)" type="text" style="font-size: 13px" icon="ChatSquare">变更
            </el-button>
          </template>
          <template v-else-if="scope.row.state === '待配送'">
            <el-button @click="changeAction(scope.row)" type="text" style="font-size: 13px" icon="ChatSquare">变更
            </el-button>
          </template>
          <template v-else-if="scope.row.state === '已送达'">
            <el-button type="text" icon="SuccessFilled" style="font-size: 13px; color: green">订单已完成</el-button>
          </template>
        </template>
      </el-table-column>

      <el-table-column label="查看更多" width="100">
        <template v-slot="scope">
          <el-button  @click="openOperatorTransportShowDialog(scope.row)" type="text" icon="Info" style="font-size: 13px">查看详情</el-button>
        </template>
      </el-table-column>

    </el-table>
    <el-pagination
        background
        layout="total, prev, pager, next"
        :total="total"
        :page-size="pageSize"
        v-model:current-page="currentPage"
        @current-change="handleCurrentChange"
        class="fixed-pagination">
    </el-pagination>

    <operator-transport-detail-dialog v-model="detailDialogVisible" :order="selectedOrder" @close="detailDialogVisible = false"
                             style="border-radius: 12px;
      display: flex;
      flex-direction: column;
      margin: 0 !important;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      max-height: calc(100% - 30px);
      max-width: calc(100% - 30px);
      justify-content: center;"/>
    <operator-transport-show-dialog
        v-model="operatorTransportShowVisible"
        :order="selectedOrder"
        @close="operatorTransportShowVisible = false"
    />

    <el-dialog title="修改运输订单" v-model="editDialogVisible" width="50%"
               style="border-radius: 12px;
      display: flex;
      flex-direction: column;
      margin: 0 !important;
      padding-right: 50px;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      max-height: calc(100% - 30px);
      max-width: calc(100% - 30px);
      justify-content: center;"
    >
      <div class="order-form-container">
        <div class="order-form-column">
          <div class="title">原信息</div>
          <el-form :model="selectedOrder">
            <el-form-item label="运费">
              <el-input-number v-model="selectedOrder.logisticsFee" style="width: 100%" disabled/>
            </el-form-item>
            <el-form-item label="备注">
              <el-input type="textarea" v-model="selectedOrder.remarks" rows="10" disabled/>
            </el-form-item>
          </el-form>
        </div>

        <div class="arrow-container">
          <span class="arrow">→</span>
        </div>

        <div class="order-form-column">
          <div class="title">新信息</div>
          <el-form :model="selectedOrder">
            <el-form-item label="运费">
              <el-input-number
                  v-model="selectedOrder.feeTemp"
                  min="0"
                  placeholder="请输入运费"    style="width: 100%"
                  :readonly="isFreightEdit"
              />
            </el-form-item>
            <el-form-item label="备注">
              <el-input type="textarea" v-model="selectedOrder.tempRemarks" placeholder="请输入备注" rows="10" :readonly="isFreightEdit"/>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" v-if="!isFreightEdit" @click="saveOrder">确认</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script>
import {ref, reactive, onMounted} from 'vue';
import {ElMessage} from "element-plus";
import {
  addOperatorTransport,
  getOperatorTransportDetail,
  listOperatorTransport,
  deleteOperatorTransport,
  updateOperatorTransport,
  confirmOperatorTransport,
} from '@/api/delivery/operatorTransport.js';
import OperatorTransportDetailDialog from "@/views/delivery/operatorTransport/operatorTransportDetailDialog.vue";
import operatorTransportShowDialog from "@/views/delivery/operatorTransport/operatorTransportShowDialog.vue";
import {updateAllocation} from "@/api/delivery/allocation.js";

export default {
  components: {operatorTransportShowDialog, OperatorTransportDetailDialog},
  setup() {
    const filters = reactive({
      trackingNumber: '',
      origin: '',
      destination: '',
      departureDate: [],
      allocationDate: [],
      state: null,
      customerType: null,
      logisticId: '',
    });

    const selectedOrder = ref({});
    const isEdit = ref(false);

    const currentTableData = ref([]);
    const total = ref(0);
    const pageSize = ref(7);
    const currentPage = ref(1);


    const operatorTransportShowVisible = ref(false);

    const openOperatorTransportShowDialog = (order) => {
      selectedOrder.value = order;
      operatorTransportShowVisible.value = true;
      console.log('1');
      console.log(order);
    };

    const dialogVisible = ref(false);

    const openDialog = (order, edit) => {
      dialogVisible.value = true;
      isEdit.value = edit;
      selectedOrder.value = order || {};
    };

    const handleSave = async (OrderData) => {
      try {
        if (isEdit.value) {
          await updateOperatorTransport(OrderData);
        } else {
          await addOperatorTransport(OrderData);
        }

        dialogVisible.value = false;
        search();
      } catch (error) {
        console.error('保存失败:', error);
      }
    };

    const handleDelete = async (row) => {
      try {
        await deleteOperatorTransport(row.trackingNumber);
        if (currentTableData.value.length === 1 && currentPage.value > 1) {
          currentPage.value -= 1;
        }
        search();
      } catch (error) {
        console.error('删除失败:', error);
      }
    };

    const detailDialogVisible = ref(false);
    const openDetailDialog = async (order) => {
      try {
        /*const response = await getOperatorTransportDetail(order);*/
        selectedOrder.value = order; // 这里要确保传递的是完整的订单对象
        detailDialogVisible.value = true; // 打开详情弹窗
        console.log(detailDialogVisible.value);
      } catch (error) {
        ElMessage.error('获取订单详情失败');
      }
    };

    const formatDate = (value) => {
      if (!value) return '';
      const date = new Date(value);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    };

    const search = async () => {
      const query = {
        trackingNumber: filters.trackingNumber,
        origin: filters.origin,
        destination: filters.destination,
        state: filters.state,
        customerType: filters.customerType,
        departStartDate: filters.allocationDate.length ? formatDate(filters.allocationDate[0]) : null,
        departEndDate: filters.allocationDate.length ? formatDate(filters.allocationDate[1]) : null,
        arriveStartDate: filters.departureDate.length ? formatDate(filters.departureDate[0]) : null,
        arriveEndDate: filters.departureDate.length ? formatDate(filters.departureDate[1]) : null,
        logisticId: filters.logisticId,
        page: currentPage.value,
        pageSize: pageSize.value,
      };
      try {
        const response = await listOperatorTransport(query);
        currentTableData.value = response.data;
        total.value = response.total;
      } catch (error) {
        ElMessage.error('获取运输订单信息失败');
        console.error('获取运输订单信息失败:', error);
      }
    };

    const selectedOrders = ref([]);

    const selectedType = ref(null);
    // 表格主选择框选中时触发
    const handleSelectionChange = (rows) => {
      if (rows.length === 0) {
        selectedType.value = null;
      }
      selectedOrders.value = rows;
      selectedType.value = selectedOrders.value[0].customerType;
    };

    const isSelectable = (row) => {
      return row.state === '待物流商确认';
    };

    const resetFilters = () => {
      filters.trackingNumber = '';
      filters.origin = '';
      filters.destination = '';
      filters.departureDate = [];
      filters.allocationDate = [];
      filters.logisticId = '';
      filters.state = null;
      filters.customerType = null;
      currentPage.value = 1;
      search();
    };

    const handleCurrentChange = (page) => {
      currentPage.value = page;
      search();
    };

    const confirmAction = async (row) => {
      try {
        // 找到对应的行
        const updatedOrder = currentTableData.value.find(item => item.trackingNumber === row.trackingNumber);
        if (updatedOrder) {
          updatedOrder.logisticsFee = row.feeTemp;
          updatedOrder.remarks = row.tempRemarks;
          updatedOrder.state = '待配送'  ; // 待配送
          await updateOperatorTransport(updatedOrder, "");
          ElMessage.success('确认接收运输订单' + row.trackingNumber);
          search(); // 刷新数据
        }
      } catch (error) {
        console.error('确认失败:', error);
      }
    };

    const editDialogVisible = ref(false);
    const isFreightEdit = ref(true);
    const originalFeeTemp = ref(null);

    const openEditDialog = (order,edit) => {
      isFreightEdit.value = !edit;
      selectedOrder.value = order;
      originalFeeTemp.value = order.feeTemp;
      editDialogVisible.value = true;
    };

    const saveOrder = async () => {
      try {
        if (selectedOrder.value.feeTemp === originalFeeTemp.value) {
          ElMessage.warning('您未修改运费金额信息');
          return; // 阻止保存操作
        }
        const order = currentTableData.value.find(item => item.trackingNumber === selectedOrder.value.trackingNumber);
        if (order) {
          order.state = "待物流商确认";
          await updateOperatorTransport(order, "edit");
          editDialogVisible.value = false;
          ElMessage.success('修改' + selectedOrder.value.trackingNumber + '成功, 等待物流商确认！');
          search(); // 刷新数据
        }
      } catch (error) {
        console.error('保存失败:', error);
      }
    };

    const table = ref(null);
    // 将当前行的选择框处于选中状态


    const logisticsInfoDialogVisible = ref(false);
    const openLogisticsInfoDialog = (order) => {
      selectedOrder.value = order;
      logisticsInfoDialogVisible.value = true;
    };

    onMounted(() => {
      search();
    });

    return {
      filters,
      currentTableData,
      total,
      pageSize,
      currentPage,
      formatDate,
      search,
      resetFilters,
      handleCurrentChange,
      openDialog,
      handleDelete,
      dialogVisible,
      selectedOrder,
      isEdit,
      handleSave,
      handleSelectionChange,
      selectedOrders,
      openDetailDialog,
      detailDialogVisible,
      selectedType,
      isSelectable,
      confirmAction,
      editDialogVisible,
      openEditDialog,
      saveOrder,
      isFreightEdit,
      table,
      openOperatorTransportShowDialog,
      operatorTransportShowVisible,
      logisticsInfoDialogVisible,
      openLogisticsInfoDialog,
    };
  },
};
</script>

<style scoped>
.order-form-container {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.order-form-column {
  width: 45%;
  padding: 20px;
  background-color: rgba(249, 249, 249, 0.63);
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
  text-align: center;
}

.arrow-container {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 24px;
  margin: 20px 0;
  align-self: center;
}

.arrow {
  font-weight: bold;
  color: #409eff;
}
.el-container {
  height: 100%;
  width: 100%;
}

.content-wrapper {
  background-color: #f5f7fa;
  min-height: inherit;
  display: flex;
}

.content-container {
  flex: 1;
  background-color: white;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
  width: calc(100% - 40px);
  box-sizing: border-box;
  border-radius: 8px;
  position: relative;
  display: flex;
  flex-direction: column;
  margin: 15px 20px;
}

.divider {
  height: 1px;
  background-color: #eaeaea;
  margin-top: 0;
  margin-bottom: 12px;
}

.dialog-footer {
  text-align: center;
}

.action-buttons {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
}

.right-aligned {
  display: flex;
  justify-content: flex-end;
}

.el-segmented {
  width: 100%;
}

.el-form-item.right:deep(.el-form-item__content) {
  justify-content: end;
}

.demo-form-inline {
  display: flex;
  flex-wrap: wrap;
  background: white;
}

.full-width {
  width: 100%;
}

.table-bottom {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}

.fixed-pagination {
  margin-top: 20px;
}

</style>
